package com.elitel.common.auth.config;

import com.elitel.common.auth.AuthProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.session.data.redis.config.annotation.SpringSessionRedisConnectionFactory;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.CookieSerializer;
import org.springframework.session.web.http.DefaultCookieSerializer;

import javax.annotation.Resource;

/**
 * redis session配置类
 * 注意：每个服务之间的RedisTemplate的序列化器必须一致，在这里我们默认使用JDK自带的序列化器
 *
 * @author: mls
 */
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
    @Value("${server.servlet.session.cookie.name}")
    public String cookieName;

    @Resource
    private AuthProperties authProperties;
    /**
     * 配置Cookie序列化
     */
    @Bean
    public CookieSerializer cookieSerializer() {
        DefaultCookieSerializer serializer = new DefaultCookieSerializer();
        // 设置Cookie名字
        serializer.setCookieName(cookieName);
        // 设置Cookie作用域Path
        serializer.setCookiePath("/");
        //设置Cookie作用域 如果有域名的话 就配置为父域名
        //serializer.setDomainName();
        serializer.setUseBase64Encoding(true);
        return serializer;
    }
    @Bean
    public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
        return new JdkSerializationRedisSerializer();
    }


    /**
     * 配置session的redis连接工厂 使session使用的redis可配置为独立的redis
     * @return
     */
    @Bean("springSessionRedisConnectionFactory")
    @SpringSessionRedisConnectionFactory
    public RedisConnectionFactory redisConnectionFactory() {
        AuthProperties.AuthRedisConfig redis = authProperties.getRedis();
        if (redis == null) {
            throw new RuntimeException("权限认证redis配置不能为空");
        }
        RedisStandaloneConfiguration conf = new RedisStandaloneConfiguration();
        conf.setHostName(redis.getHost());
        conf.setPort(redis.getPort());
        conf.setDatabase(redis.getDatabase());
        if (redis.getUsername() != null && !redis.getUsername().isEmpty()) {
            conf.setUsername(redis.getUsername());
        }
        if (redis.getPassword() != null && !redis.getPassword().isEmpty()) {
            conf.setPassword(redis.getPassword());
        }
        return new LettuceConnectionFactory(conf);
    }


}
